import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/schooladmin.dart';
import 'package:ichinesereader/controller/user.dart';
import 'package:ichinesereader/models/class/ClassDetailsDto.dart';
import 'package:ichinesereader/models/class/ClassDetailsNew.dart';
import 'package:ichinesereader/models/common/Settings.dart';
import 'package:ichinesereader/models/forms/forms.dart';
import 'package:ichinesereader/service/schooladmin.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/layouts/customAppBar.dart';
import 'package:reactive_forms/reactive_forms.dart';
import 'package:reactive_segmented_control/reactive_segmented_control.dart';
import 'package:get/get.dart';
import '../../themes/pageStyles.dart';

class TeacherClassSettings extends StatefulWidget {
  @override
  State<TeacherClassSettings> createState() => _TeacherClassSettingsState();
}

class _TeacherClassSettingsState extends State<TeacherClassSettings> {
  final box = Hive.box('appconfig');
  final SchoolAdminController _controller = Get.find();
  final UserController _usercontroller = Get.find();
  final SchoolAdminServiceProvider _service = new SchoolAdminServiceProvider();
  String classId = '';
  bool setEvaluation = true;
  bool setPlacementTest = true;
  bool setVocabulary = true;

  @override
  void initState() {
    classId = box.get(CacheManagerKey['currentclass'].toString());
    if (_controller.classDetailsNew.value.classId != null) {
      setPlacementTest =
          _controller.classDetailsNew.value.settings?.placementTest ?? true;
      setEvaluation =
          _controller.classDetailsNew.value.settings?.evaluation ?? true;
      setVocabulary =
          _controller.classDetailsNew.value.settings?.vocabulary ?? true;
    }
    super.initState();
  }

  @override
  void dispose() {
    _controller.fetchClassDetailsNewByClassId(classId);
    super.dispose();
  }

  void updateClassSettings(ClassDetailsDto dto) async {
    try {
      _controller.updateClasss(dto).then((data) {
        if (data.status == 1000) {
          box.put(CacheManagerKey['currentclassProgramId'].toString(),
              dto.programId);
          //_controller.fetchClassDetailsNewByClassId(classId);
          Get.snackbar('Message'.tr, 'Class settings updated successfully.'.tr,
              backgroundColor: Theme.of(context).primaryColor,
              colorText: Theme.of(context).primaryColorLight,
              snackPosition: SnackPosition.BOTTOM);
        } else {
          Get.snackbar('Message'.tr, 'Class settings updated failed'.tr,
              backgroundColor: Theme.of(context).primaryColor,
              colorText: Theme.of(context).primaryColorLight,
              snackPosition: SnackPosition.BOTTOM);
        }
      });
    } catch (error) {
      Get.snackbar('Message'.tr, 'Class settings updated failed'.tr,
          backgroundColor: Theme.of(context).primaryColor,
          colorText: Theme.of(context).primaryColorLight,
          snackPosition: SnackPosition.BOTTOM);
      Log.debug(error);
    }
  }

  void updateAllClassSettings(ClassDetailsDto dto) async {
    try {
      EasyLoading.show();
      if (_usercontroller.myClasses.length > 0) {
        for (var item in _usercontroller.myClasses) {
          ClassDetailsDto nDto = dto;
          nDto.classId = item.classId;
          nDto.className = item.className;
          await _service.updateClass(nDto);
          Log.debug(nDto.classId);
        }
        box.put(
            CacheManagerKey['currentclassProgramId'].toString(), dto.programId);
      }
      Get.snackbar('Message'.tr, 'Class settings updated successfully'.tr,
          backgroundColor: Theme.of(context).primaryColor,
          colorText: Theme.of(context).primaryColorLight,
          snackPosition: SnackPosition.BOTTOM);
    } catch (error) {
      Get.snackbar('Message'.tr, 'Class settings updated failed'.tr,
          backgroundColor: Theme.of(context).primaryColor,
          colorText: Theme.of(context).primaryColorLight,
          snackPosition: SnackPosition.BOTTOM);
      Log.debug(error);
    } finally {
      EasyLoading.dismiss();
    }
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build TeacherClassSettings');
    final PageStyles _pageStyles = PageStyles();

    ClassSettingsFormModel formModel = ClassSettingsFormModel();
    var form = formModel.form;

    return Scaffold(
      backgroundColor: Colors.transparent,
      appBar: CustomAppBar(title: 'Class Settings'.tr),
      body: Container(
        height: double.infinity,
        width: double.infinity,
        decoration: _pageStyles.pageBoxDecoration(),
        child: Container(
          margin: EdgeInsets.symmetric(vertical: 30.0, horizontal: 12.0),
          decoration: _pageStyles.dataGridBackground(),
          child: Container(
            margin: EdgeInsets.all(12.0),
            decoration: _pageStyles.dataGridForground(),
            child: Obx(() {
              if (_controller.classDetailsNew.value.classId != null) {
                Program _classProgram =
                    _controller.classDetailsNew.value.program as Program;
                Settings _classSettings =
                    _controller.classDetailsNew.value.settings as Settings;

                _classSettings.evaluation = setEvaluation;
                _classSettings.vocabulary = setVocabulary;
                _classSettings.placementTest = setPlacementTest;

                form.control('subprogram').value =
                    _classProgram.id ?? '570b73f2-95c9-11ec-8fc3-00ffe3295c37';
                form.control('program').value =
                    _classProgram.tree?.id ?? '59fdd7a586444f5963a55d9b';

                List<DropdownMenuItem> _subprograms = [];

                if (_classProgram.tree != null &&
                    _classProgram.tree!.lowerProgram!.isNotEmpty) {
                  _classProgram.tree!.lowerProgram?.forEach((element) {
                    _subprograms.add(
                      DropdownMenuItem(
                        value: element.id,
                        child: Text(
                          element.name.toString(),
                        ),
                      ),
                    ); //style: TextStyle(color:Color(0xff00599b),),
                  });
                } else {
                  _subprograms = Constants.nanhaiImmersionSubProgramsDropdown;
                }

                form.control('texttype').value =
                    _classSettings.language ?? 'Simplified';
                form.control('audiotype').value =
                    _classSettings.lang ?? 'Mandarin';
                form.control('pinyinenabled').value =
                    _classSettings.pinyin ?? true;
                form.control('evaluation').value =
                    _classSettings.evaluation ?? true;
                form.control('placementTest').value =
                    _classSettings.placementTest ?? true;
                form.control('vocabulary').value =
                    _classSettings.vocabulary ?? true;
                form.control('quizaudioenabled').value =
                    _classSettings.quizAudio ?? true;
                form.control('viewreport').value =
                    _controller.classDetailsNew.value.viewReport ?? true;
                form.control('interfaceChinese').value =
                    _classSettings.interfaceChinese ?? true;

                if (form.control('texttype').value == 'No text')
                  form.control('pinyinenabled').value = false;
                if (_classSettings.quizThreshold == 0)
                  form.control('quizThreshold').value = false;
                if (_classSettings.quizThreshold == 75)
                  form.control('quizThreshold').value = true;

                return SingleChildScrollView(
                  primary: false,
                  child: Padding(
                    padding: const EdgeInsets.all(21.0),
                    child: ReactiveForm(
                      formGroup: form,
                      child: Column(
                        children: <Widget>[
                          Row(
                            children: [
                              Text(
                                _controller.classDetailsNew.value.className
                                    .toString(),
                                style: Theme.of(context).textTheme.displayLarge,
                                overflow: TextOverflow.fade,
                              ),
                              Padding(
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 12.0),
                                child: Text(
                                  '(Class ID: ${_controller.classDetailsNew.value.classId.toString()})',
                                  style: Theme.of(context)
                                      .textTheme
                                      .displaySmall
                                      ?.copyWith(
                                          fontStyle: FontStyle.italic,
                                          fontSize: 12.0,
                                          color: Get.isDarkMode
                                              ? Get.theme.primaryColorDark
                                              : Colors.black),
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                            ],
                          ),
                          SizedBox(
                            height: 12,
                          ),
                          // ReactiveDropdownField<dynamic>(
                          //   elevation: 1,
                          //   //dropdownColor: Color(0xffffffe1),
                          //   formControlName: 'program',
                          //   decoration: const InputDecoration(
                          //     labelText: 'Program',
                          //     labelStyle: TextStyle(color: Colors.black),
                          //   ),
                          //   items: Constants.nanhaiPrograms,
                          //   readOnly: true,
                          //   // onChanged: (value)
                          //   // {
                          //   //   var programTree = _classProgram.tree!.lowerProgram!
                          //   //       .where((element) =>
                          //   //           element.id == value.toString())
                          //   //       .first;
                          //   //   if (programTree.lowerProgram != null) {
                          //   //     _subprograms.clear();
                          //   //     programTree.lowerProgram?.forEach((element) {
                          //   //       _subprograms.add(
                          //   //         DropdownMenuItem(
                          //   //     value: element.id,
                          //   //      child: Text(
                          //   //       element.name.toString(),
                          //   //      ),
                          //   //         ),);
                          //   //     });
                          //   //   }
                          //   // },
                          // ),

                          ReactiveDropdownField<dynamic>(
                            elevation: 1,
                            dropdownColor: Get.theme.primaryColorLight,
                            formControlName: 'subprogram',
                            decoration: InputDecoration(
                              labelText: 'Program'.tr,
                              labelStyle: TextStyle(
                                  color: Get.isDarkMode
                                      ? Colors.white
                                      : Colors.black,
                                  fontSize: 18.0),
                            ),
                            //items: _subprograms,
                            items: Constants.nanhaiSubProgramsDropdown,
                          ),
                          SizedBox(
                            height: 21,
                          ),
                          ReactiveSegmentedControl<String, String>(
                            formControlName: 'audiotype',
                            decoration: InputDecoration(
                              labelText: 'Audio'.tr,
                              border: OutlineInputBorder(),
                              helperText: '',
                            ),
                            selectedColor: Get.isDarkMode
                                ? Get.theme.primaryColorDark
                                : Get.theme.primaryColor,
                            unselectedColor: Get.isDarkMode
                                ? Get.theme.primaryColor
                                : Get.theme.primaryColorLight.withOpacity(0.3),
                            children: {
                              'Mandarin': Text(
                                'Mandarin'.tr,
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 14.0,
                                  letterSpacing: 1.0,
                                ),
                              ),
                              'Cantonese': Text(
                                'Cantonese'.tr,
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 14.0,
                                  letterSpacing: 1.0,
                                ),
                              ),
                              'No_audio': Text(
                                'No Audio'.tr,
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 14.0,
                                  letterSpacing: 1.0,
                                ),
                              ),
                            },
                          ),

                          ReactiveSegmentedControl<String, String>(
                            formControlName: 'texttype',
                            decoration: InputDecoration(
                              labelText: 'Text'.tr,
                              border: OutlineInputBorder(),
                              helperText: '',
                            ),
                            padding: const EdgeInsets.all(0.0),
                            selectedColor: Get.isDarkMode
                                ? Get.theme.primaryColorDark
                                : Get.theme.primaryColor,
                            unselectedColor: Get.isDarkMode
                                ? Get.theme.primaryColor
                                : Get.theme.primaryColorLight.withOpacity(0.3),
                            children: {
                              'Simplified': Text('Simplified'.tr,
                                  style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 14.0,
                                    letterSpacing: 1.0,
                                  )),
                              'Traditional': Text('Traditional'.tr,
                                  style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 14.0,
                                    letterSpacing: 1.0,
                                  )),
                              'No text': Text('No Text'.tr,
                                  style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 14.0,
                                    letterSpacing: 1.0,
                                  )),
                            },
                          ),
                          ReactiveSwitchListTile(
                            title: Text(
                              'Pinyin'.tr,
                              style: TextStyle(
                                  color: Get.isDarkMode
                                      ? Colors.white
                                      : Colors.black,
                                  fontSize: 18.0),
                            ),
                            subtitle: Text(
                              'When text option set to NO TEXT, pinyin can not be displayed.'
                                  .tr,
                              style: TextStyle(
                                  fontStyle: FontStyle.italic,
                                  fontSize: 12.0,
                                  color: Get.isDarkMode
                                      ? Get.theme.primaryColorDark
                                      : Colors.black),
                            ),
                            formControlName: 'pinyinenabled',
                          ),
                          ReactiveSwitchListTile(
                            title: Text(
                              'Quiz Audio'.tr,
                              style: TextStyle(
                                  color: Get.isDarkMode
                                      ? Colors.white
                                      : Colors.black,
                                  fontSize: 18.0),
                            ),
                            subtitle: Text(
                              'When enabled and audio option set to NO AUDIO, quiz will be played in Mandarin.'
                                  .tr,
                              style: TextStyle(
                                  fontStyle: FontStyle.italic,
                                  fontSize: 12.0,
                                  color: Get.isDarkMode
                                      ? Get.theme.primaryColorDark
                                      : Colors.black),
                            ),
                            formControlName: 'quizaudioenabled',
                          ),
                          ReactiveSwitchListTile(
                            title: Text(
                              'Parent Report?'.tr,
                              style: TextStyle(
                                  color: Get.isDarkMode
                                      ? Colors.white
                                      : Colors.black,
                                  fontSize: 18.0),
                            ),
                            subtitle: Text(''),
                            formControlName: 'viewreport',
                          ),
                          ReactiveSwitchListTile(
                            title: Text(
                              'Dictionary?'.tr,
                              style: TextStyle(
                                  color: Get.isDarkMode
                                      ? Colors.white
                                      : Colors.black,
                                  fontSize: 18.0),
                            ),
                            subtitle: Text(
                              'If enabled, students could use the book dictionary if available.'
                                  .tr,
                              style: TextStyle(
                                  fontStyle: FontStyle.italic,
                                  fontSize: 12.0,
                                  color: Get.isDarkMode
                                      ? Get.theme.primaryColorDark
                                      : Colors.black),
                            ),
                            formControlName: 'vocabulary',
                          ),
                          ReactiveSwitchListTile(
                            title: Text(
                              'Evaluation?'.tr,
                              style: TextStyle(
                                  color: Get.isDarkMode
                                      ? Colors.white
                                      : Colors.black,
                                  fontSize: 18.0),
                            ),
                            subtitle: Text(
                              'If enabled, evaluation books will be compulsory.'
                                  .tr,
                              style: TextStyle(
                                  fontStyle: FontStyle.italic,
                                  fontSize: 12.0,
                                  color: Get.isDarkMode
                                      ? Get.theme.primaryColorDark
                                      : Colors.black),
                            ),
                            formControlName: 'evaluation',
                          ),
                          ReactiveSwitchListTile(
                            title: Text(
                              'Placement Test?'.tr,
                              style: TextStyle(
                                  color: Get.isDarkMode
                                      ? Colors.white
                                      : Colors.black,
                                  fontSize: 18.0),
                            ),
                            subtitle: Text(
                              'If enabled, placement test will be compulsory when students log in first time.'
                                  .tr,
                              style: TextStyle(
                                  fontStyle: FontStyle.italic,
                                  fontSize: 12.0,
                                  color: Get.isDarkMode
                                      ? Get.theme.primaryColorDark
                                      : Colors.black),
                            ),
                            formControlName: 'placementTest',
                          ),
                          ReactiveSwitchListTile(
                            title: Text(
                              'Interface Chinese?'.tr,
                              style: TextStyle(
                                  color: Get.isDarkMode
                                      ? Colors.white
                                      : Colors.black,
                                  fontSize: 18.0),
                            ),
                            subtitle: Text(
                              'Ifenabledinterface'.tr,
                              style: TextStyle(
                                  fontStyle: FontStyle.italic,
                                  fontSize: 12.0,
                                  color: Get.isDarkMode
                                      ? Get.theme.primaryColorDark
                                      : Colors.black),
                            ),
                            formControlName: 'interfaceChinese',
                          ),
                          ReactiveSwitchListTile(
                            title: Text(
                              'Quiz Threshhold?'.tr,
                              style: TextStyle(
                                  color: Get.isDarkMode
                                      ? Colors.white
                                      : Colors.black,
                                  fontSize: 18.0),
                            ),
                            subtitle: Text(
                              'Ifenabledquiz'.tr,
                              style: TextStyle(
                                  fontStyle: FontStyle.italic,
                                  fontSize: 12.0,
                                  color: Get.isDarkMode
                                      ? Get.theme.primaryColorDark
                                      : Colors.black),
                            ),
                            formControlName: 'quizThreshold',
                          ),
                          Padding(
                            padding: const EdgeInsets.only(top: 21.0),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                Spacer(),
                                Obx(() {
                                  if (_usercontroller.myClasses.isNotEmpty &&
                                      _usercontroller.myClasses.length > 1) {
                                    return ReactiveFormConsumer(
                                      builder: (context, form, child) {
                                        ClassDetailsDto dto =
                                            new ClassDetailsDto();
                                        dto.classId = classId;
                                        dto.className = _controller
                                            .classDetailsNew.value.className;
                                        dto.level = _controller
                                            .classDetailsNew.value.level;
                                        dto.programId =
                                            form.control('subprogram').value;
                                        dto.settings = new Settings();
                                        dto.settings?.pinyin =
                                            form.control('pinyinenabled').value;
                                        dto.settings?.quizAudio = form
                                            .control('quizaudioenabled')
                                            .value;
                                        dto.settings?.placementTest =
                                            form.control('placementTest').value;
                                        dto.settings?.evaluation =
                                            form.control('evaluation').value;
                                        dto.settings?.vocabulary =
                                            form.control('vocabulary').value;
                                        dto.settings?.lang =
                                            form.control('audiotype').value;
                                        dto.settings?.language =
                                            form.control('texttype').value;
                                        dto.viewReport =
                                            form.control('viewreport').value;
                                        dto.settings?.interfaceChinese = form
                                            .control('interfaceChinese')
                                            .value;
                                        if (form
                                                .control('quizThreshold')
                                                .value ==
                                            false)
                                          dto.settings?..quizThreshold = 0;
                                        if (form
                                                .control('quizThreshold')
                                                .value ==
                                            true)
                                          dto.settings?.quizThreshold = 75;

                                        return Padding(
                                          padding: const EdgeInsets.symmetric(
                                              horizontal: 12.0),
                                          child: ElevatedButton(
                                              child: Text(
                                                'Apply to all classes'.tr,
                                                style: TextStyle(
                                                  fontSize: 14.0,
                                                  color: Get.isDarkMode
                                                      ? Get.theme
                                                          .primaryColorDark
                                                      : Get.theme
                                                          .primaryColorLight,
                                                  letterSpacing: 1.0,
                                                ),
                                              ),
                                              onPressed: () {
                                                if (form.valid) {
                                                  Log.debug(form.value);
                                                  updateAllClassSettings(dto);
                                                }
                                              }),
                                        );
                                      },
                                    );
                                  } else {
                                    return Visibility(
                                      child: Text(''),
                                      visible: false,
                                    );
                                  }
                                }),
                                ReactiveFormConsumer(
                                  builder: (context, form, child) {
                                    ClassDetailsDto dto = new ClassDetailsDto();
                                    dto.classId = classId;
                                    dto.className = _controller
                                        .classDetailsNew.value.className;
                                    dto.level =
                                        _controller.classDetailsNew.value.level;
                                    dto.programId =
                                        form.control('subprogram').value;
                                    dto.settings = new Settings();
                                    dto.settings?.pinyin =
                                        form.control('pinyinenabled').value;
                                    dto.settings?.quizAudio =
                                        form.control('quizaudioenabled').value;
                                    dto.settings?.lang =
                                        form.control('audiotype').value;
                                    dto.settings?.language =
                                        form.control('texttype').value;
                                    dto.viewReport =
                                        form.control('viewreport').value;
                                    dto.settings?.pinyin =
                                        form.control('pinyinenabled').value;
                                    dto.settings?.quizAudio =
                                        form.control('quizaudioenabled').value;
                                    dto.settings?.placementTest =
                                        form.control('placementTest').value;
                                    dto.settings?.evaluation =
                                        form.control('evaluation').value;
                                    dto.settings?.vocabulary =
                                        form.control('vocabulary').value;
                                    dto.settings?.interfaceChinese =
                                        form.control('interfaceChinese').value;
                                    if (form.control('quizThreshold').value ==
                                        false) dto.settings?..quizThreshold = 0;
                                    if (form.control('quizThreshold').value ==
                                        true) dto.settings?.quizThreshold = 75;

                                    return ElevatedButton(
                                        child: Text(
                                          'Submit'.tr,
                                          style: TextStyle(
                                            fontSize: 14.0,
                                            color: Get.isDarkMode
                                                ? Get.theme.primaryColorDark
                                                : Get.theme.primaryColorLight,
                                            letterSpacing: 1.0,
                                          ),
                                        ),
                                        onPressed: () {
                                          if (form.valid) {
                                            Log.debug(form.value);
                                            updateClassSettings(dto);
                                          }
                                        });
                                  },
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                );
              } else {
                return Text('');
              }
            }),
          ),
        ),
      ),
    );
  }
}
